package cn.life.business.apply.service.impl;


import cn.life.business.apply.dao.ApplyDao;
import cn.life.business.apply.entity.po.ApplyDetailPo;
import cn.life.business.apply.entity.po.ApplyPo;
import cn.life.business.apply.entity.vo.ApplyVo;
import cn.life.business.apply.service.ApplyService;
import cn.life.business.audit.dao.AuditDao;
import cn.life.business.audit.entity.po.AuditPo;
import cn.life.common.entity.model.CMessage;
import cn.life.common.entity.po.MessagePo;
import cn.life.common.entity.vo.Pagination;
import cn.life.common.utils.PDF.apply.ApplyTemplate;
import cn.life.common.utils.message.ALiBaBaUtils;
import com.aliyuncs.exceptions.ClientException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 王振宇
 * @Description:
 * @Date 2018-09-18 14:29:37
 */
@Service
@Transactional
public class ApplyServiceImpl implements ApplyService {

    @Autowired
    private ApplyDao applyDao;

    @Autowired
    private AuditDao auditDao;


    @Override
    public CMessage AddApply(HttpServletRequest request, ApplyPo applyPo) {
        //1.查询当前钱类型下增加数量，用于生成编号
        int num=applyDao.queryAdvertisement(applyPo);
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMdd");
        String date=simpleDateFormat.format(applyPo.getOprDate());
        String applyNo = date+"0"+applyPo.getApplyType()+"00"+num;
        applyPo.setApplyNo(applyNo);
        //2.新增主表信息
        Long applyId = applyDao.addApply(applyPo);
        if (applyId != null) {
            //3.新增明细表集合信息
            List<ApplyDetailPo> detailPos = new ArrayList<>();
            List<ApplyDetailPo> detailList = applyPo.getDetailList();
            if(detailList != null && detailList.size() > 0){
                for(ApplyDetailPo detail  : detailList){
                    if(detail != null && !detail.getImgUrl().equals("")){
                        ApplyDetailPo detailPo = new ApplyDetailPo();
                        detailPo.setApplyId(applyId);
                        detailPo.setImgUrl(detail.getImgUrl());
                        detailPo.setImgType(detail.getImgType());
                        detailPos.add(detailPo);
                    }
                }
            }
            applyDao.addApplyDetailList(detailPos);
            try {
                String pdfPrefixUrl = request.getServletContext().getRealPath("/");
                boolean res = new ApplyTemplate().exportPdf(pdfPrefixUrl + "/pdf/" + applyNo + ".pdf",pdfPrefixUrl + "/img/time.jpg",applyPo);
                if(!res) {
                    return CMessage.fail("导出PDF异常，请联系管理人员");
                }
            } catch (Exception e) {
                e.printStackTrace();
                return CMessage.fail("导出PDF异常，请联系管理人员");
            }
            return CMessage.successByMsg("新增成功");
        } else {
            return CMessage.addFail();
        }

    }

    @Override
    public CMessage queryList(ApplyVo applyVo) {
        Pagination<ApplyVo> list = applyDao.queryList(applyVo);
        return CMessage.successByData(list);
    }

    @Override
    public CMessage querySingle(ApplyVo applyVo) {
        //1.查询主表信息
        applyVo = applyDao.queryApplyInfo(applyVo);
        //2.查询明细图片信息
        List<ApplyDetailPo> list = applyDao.queryAppliDetailList(applyVo);
        applyVo.setList(list);
        //3.将明细集合信息转为imgUrls串放入返回的imgUrl中
        String imgUrls = "";
        if(list.size() > 0){
            for(ApplyDetailPo detailPo : list){
                imgUrls = imgUrls + detailPo.getImgUrl() + ",";
            }
        }
        applyVo.setImgUrl(imgUrls);

        return CMessage.successByData(applyVo);
    }

    @Override
    public CMessage update(ApplyPo applyPo) {
        Long id = applyPo.getApplyId();
        if (id != null) {
            AuditPo auditPo = new AuditPo();
            auditPo.setApplyId(id);
            auditPo.setAuditState(0);
            auditPo.setApplyNo(applyPo.getApplyNo());
            auditDao.updateAudit(auditPo);
            applyDao.updateApply(applyPo);
            //3.修改明细图片信息
            applyDao.deleteApplyImg(applyPo);
            if(applyPo.getDetailList() != null && applyPo.getDetailList().size() > 0){
                applyDao.addApplyDetailList(applyPo.getDetailList());
            }
            //4.修改审查状态
            applyDao.updateAuditState(applyPo);
            return CMessage.modifySuccess();

        } else {
            return CMessage.modifyFail();
        }
    }

    @Override
    public CMessage delete(ApplyPo applyPo) {
        if (applyDao.deleteApply(applyPo) == 1 && applyDao.deleteApplyImg(applyPo) == 1) {
            return CMessage.removeSuccess();
        } else {
            return CMessage.removeFail();
        }

    }

    @Override
    public List<ApplyVo> Excel(ApplyVo applyVo) {
        List<ApplyVo> list = applyDao.Excel(applyVo);
        return list;
    }

    @Override
    public CMessage addApplyAudit(ApplyPo applyPo) {
        ApplyVo applyVo = new ApplyVo();
        applyVo.setApplyId(applyPo.getApplyId());
        //1.查询记录信息
        applyVo = applyDao.queryApplyInfo(applyVo);
        //2.修改盖章图片路径信息
        applyDao.updateApplyCertifiedImgUrl(applyPo);
        //3.新增审查信息
        AuditPo auditPo = new AuditPo();
        auditPo.setApplyId(applyPo.getApplyId());
        AuditPo auditRec = auditDao.queryAuditInfo(auditPo);
        if(auditRec == null){
            auditPo.setApplyId(applyVo.getApplyId());
            auditPo.setApplyNo(applyVo.getApplyNo());
            auditPo.setOprUserId(applyPo.getOprUserId());
            auditPo.setOprUserName(applyPo.getOprUserName());
            auditPo.setAuditState(0);
            auditPo.setOprDate(applyPo.getOprDate());
            auditDao.addAudit(auditPo);
        }else{
            auditDao.updateOnlyState(auditPo);
        }
        try {
            String auditPers = applyDao.getAuditPerPhone();
            MessagePo messagePo = new MessagePo();
            messagePo.setPhone(auditPers);
            messagePo.setName("(编号:" + applyVo.getApplyNo() + ")");
            new ALiBaBaUtils().sendAwaitingAuditMessage(messagePo);
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return CMessage.successByMsg("提交审查成功");
    }

    @Override
    public CMessage exportPdf(HttpServletRequest request,ApplyVo applyVo) {
        String pdfPrefixUrl = request.getServletContext().getRealPath("/");
        String pdfUrl = pdfPrefixUrl + "/pdf/" + applyVo.getApplyNo() + ".pdf";
        File pfdFile = new File(pdfUrl);
        //不存在则创建
        ApplyPo applyPo = new ApplyPo();
        //1.查询主表信息
        applyVo = applyDao.queryApplyInfo(applyVo);
        //2.查询明细图片信息
        List<ApplyDetailPo> list = applyDao.queryAppliDetailList(applyVo);
        //3.赋值
        BeanUtils.copyProperties(applyVo,applyPo);
        applyPo.setDetailList(list);
        try {
            boolean res = new ApplyTemplate().exportPdf(pdfPrefixUrl + "/pdf/" + applyVo.getApplyNo() + ".pdf",pdfPrefixUrl + "/img/time.jpg",applyPo);
            if(res){
                return CMessage.success();
            }else{
                return CMessage.fail("导出PDF异常，请联系管理人员");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return CMessage.fail("导出PDF异常，请联系管理人员");
        }
    }

    @Override
    public CMessage sendMessage(MessagePo messagePo) {
        try {
            String code = new ALiBaBaUtils().sendMessage(messagePo);
            if(code == null){
                return CMessage.fail("获取短信验证失败，请联系管理人员");
            }
            messagePo.setCode(code);
            int res = applyDao.addPhoneMessage(messagePo);
            if(res == 1){
                return CMessage.successByMsg("短信已发送，请查收");
            }
        } catch (ClientException e) {
            e.printStackTrace();
            return CMessage.fail("获取短信验证失败，请联系管理人员");
        }
        return CMessage.fail("获取短信验证失败，请联系管理人员");
    }

    @Override
    public CMessage checkMessage(MessagePo messagePo) {
        boolean res = applyDao.checkPhoneMessage(messagePo);
        if(res){
            return CMessage.success();
        }
        return CMessage.fail("短信验证码错误");
    }


}
